<?php
require_once 'lib/rdbms_viewer.class.php';
require_once 'lib/generic_data_pager.class.php';
require_once 'Structures/DataGrid.php';

$rdbms_dsn  =   array(
                        'phptype'  => 'mysql',
                        'username' => 'root',
                        'password' => '',       
                        'hostspec' => 'localhost',
                        'database' => 'viewer_os'
                     );                

$options    =   array('dsns' =>  array('rdbms_viewer' => $rdbms_dsn));
$rdbms      =   new rdbms_viewer($options);
       

/* clean cgi */
$dbhs_index =   $rdbms_dsn['username'].'@'.$rdbms_dsn['hostspec'];

$dsn_id     =   $rdbms->dbhs[$dbhs_index]->quote($_GET['dsn_id'], 'integer', false);
$table      =   $rdbms->dbhs[$dbhs_index]->quote($_GET['table'], 'text', false);
$database   =   $rdbms->dbhs[$dbhs_index]->quote(@$_GET['database'], 'text', false);

/* fetch DSN */
$dsn        =   $rdbms->fetch_dsn($dsn_id);
$dsn['database']    =   (!empty($dsn['database']) && !is_null($dsn['database'])) 
                        ? $dsn['database'] : $database;
                        
// Some PEAR classes don't like extra crap in their dsn options and since this
// dsn is pulled straight out of the viewer dsn table, it contains a few other
// attributes like dsn_id, created, updated.  To maintain flexibility with other 
// parts of the codebase that depend on this behavior, the DSN must be boiled down here.
//
// This might change in the future but it's not the most important decision I 
// will be making today..
$dsn        =   array(
                        'phptype'  => $dsn['phptype'],
                        'username' => $dsn['username'],
                        'password' => $dsn['password'],       
                        'hostspec' => $dsn['hostspec'],
                        'database' => $dsn['database']
                     );  



/* init generic pager */
$options    =   array(  'dsn'   =>  $dsn,
                        'table' =>  $table,
                        'primary_key'   =>  ''              
                        );

$limit  =   (isset($_REQUEST['limit'])) ? strip_tags($_REQUEST['limit']) : 25;
                        
$pager      =   new generic_data_pager($options);
$datagrid   =&  new Structures_DataGrid($limit);

// if using extjs paging toolbar component
if($current_page = $pager->get_initial_page_index_from_extjs()) {
    $datagrid->setCurrentPage($current_page);
}

$datagrid->bindDataSource($pager);

$datagrid->fill($pager->pager);

$columns        =   $datagrid->getColumns();

$result_data    =   $datagrid->recordSet;   // not sure the best route to get this
$pager->set_result_data_attributes($columns);
$pager->set_result_data($result_data);

echo $pager->build_extstore_json();
error_log(var_export($_POST, true));
?>
